package cn.onecloud.examples;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Keijack
 *
 */
@Repository
@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
public class StudentDao {

    @Autowired
    private SessionFactory sessionFactory;

    public Student get(Integer id) {
	return (Student) session().get(Student.class, id);
    }

    private Session session() {
	return this.sessionFactory.getCurrentSession();
    }

    @SuppressWarnings("unchecked")
    public List<Student> query(String nameLike) {
	String hql = "from Student";
	if (StringUtils.isNotBlank(nameLike)) {
	    hql += " where name like :nameLike";
	}
	Query query = session().createQuery(hql);

	if (StringUtils.isNotBlank(nameLike)) {
	    query.setString("nameLike", "%" + nameLike + "%");
	}
	return query.list();
    }

    public void add(Student student) {
	this.session().save(student);
    }

    public void update(Student student) {
	this.session().update(student);
    }
}
